<script setup lang="tsx">
import {ref} from 'vue';
import {useBoolean, useLoading} from '@sa/hooks';
import {useAppStore} from '@/store/modules/app';
import {$t} from '@/locales';
import TemplateOperateDrawer from "@/views/templates/template-operate-drawer.vue";
import {fetchDeleteTemplate, fetchGetTemplatePage} from "@/service/api/template";
import {useRouterPush} from "@/hooks/common/router";
import {NButton, NPopconfirm} from "naive-ui";


const {routerPushByKey} = useRouterPush();
defineOptions({name: 'TemplateList'})
const appStore = useAppStore();
const {bool: drawerVisible, setTrue: openDrawer} = useBoolean();
const {loading, startLoading, endLoading} = useLoading();
const columns = ref<any[]>([
  {
    type: 'selection',
    align: 'center',
    width: 48
  },
  {
    key: 'name',
    title: '模板名称',
    align: 'center',
  },
  {
    key: 'company.name',
    title: '所属公司',
    align: 'center',
  },
  {
    key: 'isDefault',
    title: '是否使用中',
    align: 'center',
  },
  {
    key: 'operate',
    title: $t('common.operate'),
    align: 'center',
    render: function (row: Api.Entity.Template | any) {
      return (
        <div class="flex-center gap-8px">
          <NButton type="primary" ghost size="tiny" onClick={() => handleTemplateDesign(row.id)}>
            {$t('common.edit')}
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
            {{
              default: () => $t('common.confirmDelete'),
              trigger: () => (
                <NButton type="error" ghost size="tiny">
                  {$t('common.delete')}
                </NButton>
              )
            }}
          </NPopconfirm>
        </div>
      )
    }
  }
]);
const data = ref<Api.Entity.Template[]>();
const pagination = ref<Api.Common.Pageable>({
    pageSize: 15,
    pageNumber: 1,
    searchProperty: null,
    searchValue: null,
    orderProperty: null,
    orderDirection: null,
    filters: null
  }
);
const checkedRowKeys = ref<string[]>([]);
const editingData = ref<Api.Entity.Template | null>(null);
const templateId = ref<number>(0)
const operateType = ref<Api.Common.OperateType>('add');

async function getData() {
  startLoading();
  const res = await fetchGetTemplatePage(pagination.value);
  data.value = res.data?.content || [];
  endLoading();
}

function handleAdd() {
  operateType.value = 'add';
  openDrawer();
}

// function handleEdit(id: number) {
//   operateType.value = 'edit';
//   if (data.value) {
//     editingData.value = data.value.find(item => item.id === id) || null;
//   }
//   openDrawer();
// }

async function handleTemplateDesign(id: number) {
  templateId.value = id;
  await routerPushByKey('common_templatedesign', {
    query: {
      templateId: id
    },
  })
}
// async function handleWorkflowDesign(id: number) {
//   templateId.value = id;
//   await routerPushByKey('common_workflowdesign', {
//     query: {
//       templateId: id
//     },
//   })
// }

async function handleDelete(id: number) {
  const {error} = await fetchDeleteTemplate([id]);
  if (!error) {
    window.$message?.success($t('common.deleteSuccess'));
    await getData();
  }
}

function refresh() {

}

getData()
</script>

<template>
  <div class="flex-vertical-stretch gap-16px overflow-hidden <sm:overflow-auto">
    <NCard title="" :bordered="false" size="small" class="card-wrapper sm:flex-1-hidden">
      <template #header>
        <NSpace wrap justify="end" class="<sm:w-200px">
          <NButton size="small" type="primary" @click="handleAdd">
            <template #icon>
              <icon-ic-round-plus class="text-icon"/>
            </template>
            {{ $t('common.add') }}
          </NButton>
          <NButton size="small" @click="refresh">
            <template #icon>
              <icon-mdi-refresh class="text-icon" :class="{ 'animate-spin': loading }"/>
            </template>
            {{ $t('common.refresh') }}
          </NButton>
        </NSpace>
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :bordered="false"
        :single-line="false"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="640"
        :loading="loading"
        :pagination="pagination"
        :row-key="(item:Api.Entity.Template) => item.id"
        class="sm:h-full"
      />
      <TemplateOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getData"
      />
    </NCard>
  </div>
</template>

<style scoped>
:deep(.n-card__content) {
  padding: 0 !important;
}

.flex-vertical-stretch {
  height: calc(100vh - 135px);
}

</style>
